<template>
  <div>WebSocket</div>
  <button @click="connect_ws">websocket</button>
</template>

<script setup>
import { ref, onMounted } from "vue";

const ws_path = ref("ws://127.0.0.1:3000");
const ws = ref({});

const connect_ws = () => {
  ws.value = new WebSocket(ws_path.value);
  //监听是否连接成功
  ws.value.onopen = () => {
    console.log("ws连接状态：" + ws.value.readyState);
    //连接成功则发送一个数据
    ws.value.send("连接成功");
  };

  //接听服务器发回的信息并处理展示
  ws.value.onmessage = (data) => {
    console.log("接收到来自服务器的消息：", data);
  };

  //监听连接关闭事件
  ws.value.onclose = () => {
    //监听整个过程中websocket的状态
    console.log("ws连接状态：" + ws.value.readyState);
  };

  //监听并处理error事件
  ws.value.onerror = (error) => {
    console.log(error);
  };
};

onMounted(() => {
  //   connect_ws();
});
</script>

<style>
</style>